package com.hualan.sfzy.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hualan.sfzy.utils.Result;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传、文件下载、文件预览控制层
 */
@RestController
public class FileController {
    private String rootPath = "d:/upload";

    private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tAXBReSgFmqQyZiWSP3";
    private static final String accessKeySecret = "2fH3qelzDdc5UJGbBuHiISOgJHai1n";
    private static final String bucketName = "sfzy-ppp";
    /**
     * 单文件上传
     *
     * @param file 封装异步提交过来的文件数据的对象
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public Result fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件!");
        }
// 获取上传的文件的文件名
        String fileName = file.getOriginalFilename();
// 处理文件重名问题: 截取文件扩展名，用UUID替代文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + suffix;
// 当前日期文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateDirPath = sdf.format(new Date());
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String objectName = dateDirPath + "/";
        try {
            ossClient.putObject(bucketName, objectName + fileName, file.getInputStream());
            return Result.success("https://sfzy-ppp.oss-cn-hangzhou.aliyuncs.com/" + objectName + fileName);
        } catch (IOException e) {
            return Result.error("文件上传错误!");
        } finally {
            ossClient.shutdown();
        }


    }

    /**
     * 文件下载
     *
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping("/download")
    public void fileDownload(String filePath, HttpServletResponse response,
                             HttpSession session) throws IOException {



// 创建输入流，读取文件
        FileInputStream fis = new FileInputStream(rootPath + "/" + filePath);
// 设置响应头信息
        response.setHeader("Content-Disposition", "attachement;filename=" +
                filePath.substring(filePath.lastIndexOf("/") + 1));
// 获取输出流
        ServletOutputStream out = response.getOutputStream();
// 拷贝
        IOUtils.copy(fis, out);
    }
}